<script setup lang="ts">
import {useRouter} from 'vue-router'
import {onMounted, ref} from 'vue'
import type {UploaderFileListItem} from 'vant'
import {showSuccessToast, showToast} from 'vant'
import {toFileUrl, uploadFileAPI} from '@/api/system/file'
import type {API} from "@/type/type";
import {getUserInfoAPI} from "@/api/auth";
import {updateUserInfoAPI} from "@/api/system/user";
import {useAuthStore} from "@/stores/auth";

const router = useRouter()

const userInfo = ref<API.ICurrentUser>({} as API.ICurrentUser)
const showPicker = ref(false)
const submitting = ref(false)
const avatarUrls = ref<UploaderFileListItem[]>([])
const authStore = useAuthStore()

const setCurrentUser = async () => {
  const {data} = await getUserInfoAPI()
  if (data) {
    userInfo.value = data
    avatarUrls.value = [{url: toFileUrl(userInfo.value.avatar), isImage: true}]
  }
}

onMounted(() => {
  setCurrentUser()
})

// 确认选择日期
const onConfirm = ({selectedValues}: { selectedValues: string[] }) => {
  if (!userInfo.value) {
    return
  }
  userInfo.value.birthday = selectedValues.join('/')
  showPicker.value = false
}

const uploadAvatar = async (file: any) => {
  const {data} = await uploadFileAPI(file.file)
  if (data) {
    showToast('上传成功')
    userInfo.value.avatar = data.id
  }
}
const onSubmit = async () => {
  try {
    submitting.value = true
    const {data} = await updateUserInfoAPI(userInfo.value)
    if (data) {
      showSuccessToast('资料更新成功')
      authStore.setCurrentUser()
      router.push('/personal')
    }
  } catch (error) {
    console.error('更新失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="edit-profile-page">
    <van-nav-bar
        title="编辑资料"
        left-text="返回"
        left-arrow
        @click-left="router.push('/personal')"
        fixed
        placeholder
    />

    <van-form
        @submit="onSubmit"
        class="profile-form"
    >
      <!-- 头像上传 -->
      <div class="form-section">
        <div class="section-title">头像</div>
        <van-uploader
            v-model="avatarUrls"
            :max-count="1"
            :preview-full-image="true"
            class="avatar-uploader"
            upload-text="更换头像"
            :after-read="uploadAvatar as any"
        >
          <template #preview-cover="{  }">
            <div class="preview-cover">点击修改</div>
          </template>
        </van-uploader>
      </div>

      <!-- 昵称 -->
      <van-field
          v-model="userInfo.nickname"
          name="nickname"
          label="昵称"
          placeholder="请输入您的昵称"
          :rules="[{ required: true, message: '请填写昵称' }]"
          class="custom-field"
      >
        <template #left-icon>
          <van-icon name="user-o" class="field-icon"/>
        </template>
      </van-field>

      <!-- 个人介绍 -->
      <van-field
          v-model="userInfo.introduction"
          name="introduction"
          label="个人介绍"
          type="textarea"
          placeholder="介绍一下自己吧~"
          rows="3"
          autosize
          maxlength="100"
          show-word-limit
          class="custom-field introduction-field"
      >
        <template #left-icon>
          <van-icon name="comment-o" class="field-icon"/>
        </template>
      </van-field>

      <!-- 性别 -->
      <van-field
          name="sex"
          label="性别"
          class="custom-field"
      >
        <template #left-icon>
          <van-icon name="friends-o" class="field-icon"/>
        </template>
        <template #input>
          <van-radio-group v-model="userInfo.sex" class="gender-radio">
            <van-radio name="0" shape="square" class="gender-option">男</van-radio>
            <van-radio name="1" shape="square" class="gender-option">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <!-- 出生日期 -->
      <van-field
          :model-value="userInfo.birthday as any"
          is-link
          readonly
          name="birthday"
          label="出生日期"
          placeholder="请选择您的出生日期"
          @click="showPicker = true"
          class="custom-field"
      >
        <template #left-icon>
          <van-icon name="calender-o" class="field-icon"/>
        </template>
      </van-field>

      <van-popup
          v-model:show="showPicker"
          position="bottom"
          round
          :style="{ height: '40%' }"
      >
        <van-date-picker
            title="选择出生日期"
            @confirm="onConfirm"
            @cancel="showPicker = false"
        />
      </van-popup>

      <!-- 提交按钮 -->
      <div class="submit-btn">
        <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="submitting"
            loading-text="提交中..."
        >
          保存修改
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped lang="less">
/* 样式保持不变 */
.edit-profile-page {
  background-color: #f7f8fa;
  min-height: 100vh;

  .profile-form {
    padding: 16px;
  }

  .form-section {
    margin-bottom: 24px;

    .section-title {
      font-size: 14px;
      color: #969799;
      margin-bottom: 12px;
      padding-left: 8px;
    }
  }

  .avatar-uploader {
    display: flex;
    justify-content: center;

    :deep(.van-uploader__upload) {
      width: 100px;
      height: 100px;
      margin: 0;
      border-radius: 50%;
      background-color: #f2f3f5;
    }

    :deep(.van-uploader__preview-image) {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      border: 2px solid #fff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .preview-cover {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      font-size: 12px;
      text-align: center;
      padding: 4px 0;
      border-bottom-left-radius: 50px;
      border-bottom-right-radius: 50px;
    }
  }

  .custom-field {
    margin-bottom: 16px;
    background-color: white;
    border-radius: 8px;
    padding: 12px 16px;

    :deep(.van-field__label) {
      width: 80px;
    }

    :deep(.van-field__value) {
      margin-left: 8px;
    }

    &.introduction-field {
      :deep(.van-field__word-limit) {
        text-align: right;
        margin-top: 4px;
        color: #969799;
      }
    }
  }

  .field-icon {
    margin-right: 8px;
    color: var(--van-blue);
    font-size: 18px;
  }

  .gender-radio {
    display: flex;
    gap: 20px;

    .gender-option {
      :deep(.van-radio__label) {
        margin-left: 4px;
      }
    }
  }

  .submit-btn {
    margin-top: 32px;
    padding: 0 16px;

    :deep(.van-button) {
      height: 44px;
      font-size: 16px;
    }
  }
}
</style>
